<?php
declare (strict_types=1);

namespace app\common\model;

use Exception;
use think\Collection;
use think\facade\Cache;

class FeedbackField extends CommonBase
{
    private const _CACHE_KEY = '%s_feedback_form_fields';

    public function getAllFeedbackField(array $where = []): array
    {
        $cacheKey           = sprintf(self::_CACHE_KEY, $this->connection);
        $feedbackFormFields = Cache::get($cacheKey);
        if (empty($moduleFields)) {
            $feedbackFormFields = $this->where(['is_delete' => config('status.mysql.table_normal')])->order('sort asc')->select()->toArray();
            Cache::set($cacheKey, $feedbackFormFields,self::CACHE_EXPIRE_TIME);
        }

        $res = [];
        foreach ($feedbackFormFields as $feedbackFormField) {
            $flag = true;
            foreach ($where as $key => $value) {
                if (is_array($value) && count($value) == 3 && $value[1] == 'in' && is_array($value[2])) {
                    if (!in_array($feedbackFormField[$value[0]], $value[2])) {
                        $flag = false;
                        break;
                    }
                } else if ($feedbackFormField[$key] != $value) {
                    $flag = false;
                    break;
                }
            }

            if ($flag) {
                $res[] = $feedbackFormField;
            }
        }

        return $res;
    }

    public function getFeedbackFieldList(int $page = 1, int $limit = 10, array $where = []): Collection
    {
        $where['is_delete'] = config('status.mysql.table_normal');
        $offset             = ($page - 1) * $limit;
        return $this->where($where)->order('sort asc')->limit($offset, $limit)->select();
    }

    public function getFeedbackFieldCount(array $where = []): int
    {
        $where['is_delete'] = config('status.mysql.table_normal');
        return $this->where($where)->count();
    }

    public function findFeedbackFieldById(int $id)
    {
        return $this->where(['id' => $id, 'is_delete' => config('status.mysql.table_normal')])->find();
    }

    public function findFeedbackFieldByCode(int $formId, string $code)
    {
        return $this->where(['form_id' => $formId, 'code' => $code, 'is_delete' => config('status.mysql.table_normal')])->find();
    }

    public function addFeedbackField(array $data): bool
    {
        $data['is_delete'] = config('status.mysql.table_normal');
        unset($data['website_code']);

        $feedbackFieldObj = $this->where(['form_id' => $data['form_id'], 'is_delete' => config('status.mysql.table_delete'), 'code' => $data['code']])->find();
        if (!empty($feedbackFieldObj)) {
            $data['created_at'] = date('Y-m-d H:i:s');
            $data['updated_at'] = date('Y-m-d H:i:s');
            $feedbackField      = $feedbackFieldObj->toArray();
            return (boolean)$this->where(['id' => $feedbackField['id']])->save(
                array_merge($feedbackField, $data)
            );
        }

        $res = (boolean)$this->save($data);
        Cache::delete(sprintf(self::_CACHE_KEY, $this->connection));
        return $res;
    }

    public function updateFeedbackField(int $id, array $data): bool
    {
        $data['updated_at'] = date('Y-m-d H:i:s');
        $res                = (boolean)$this->where(['id' => $id])->save($data);
        Cache::delete(sprintf(self::_CACHE_KEY, $this->connection));
        return $res;
    }

    /**
     * @throws Exception
     */
    public function batchFeedbackFieldSort(array $data): bool
    {
        try {
            $this->startTrans();
            foreach ($data as $id => $sort) {
                $this->where('id', $id)->update(['sort' => $sort]);
            }
            $this->commit();
            Cache::delete(sprintf(self::_CACHE_KEY, $this->connection));
            return true;
        } catch (Exception $e) {
            $this->rollback();
            throw new Exception($e->getMessage());
        }
    }

    /**
     * @throws Exception
     */
    public function deleteFeedbackField(int $id): bool
    {
        try {
            $this->startTrans();
            $feedbackFieldObj = $this->findFeedbackFieldById($id);
            if (empty($feedbackFieldObj)) {
                return false;
            }
            $feedbackField = $feedbackFieldObj->toArray();

            // 留言表单标识
            $feedbackFormObj = $this->name( 'feedback_form')->where([
                'id'        => $feedbackField['form_id'],
                'is_delete' => config('status.mysql.table_normal'),
            ])->find();
            if (empty($feedbackFormObj)) {
                throw new Exception('get feedback form error');
            }
            $feedbackForm = $feedbackFormObj->toArray();

            $tableName = 'feedback_' . $feedbackForm['form_code'] . '_' . self::FIELD_TYPE_DB_SUFFIX_MAP[$feedbackField['field_type']];
            $this->name($tableName)->where([
                'field_id'  => $feedbackField['id'],
                'is_delete' => config('status.mysql.table_normal'),
            ])->save(['is_delete' => config('status.mysql.table_delete')]);

            $this->where(['id' => $id])->save(['is_delete' => config('status.mysql.table_delete')]);
            $this->commit();
            Cache::delete(sprintf(self::_CACHE_KEY, $this->connection));
            return true;
        } catch (Exception $e) {
            $this->rollback();
            throw new Exception($e->getMessage());
        }
    }

    public function clearFeedbackFieldCache(): bool
    {
        return Cache::delete(sprintf(self::_CACHE_KEY, $this->connection));
    }
}
